package com.seata.demo.service.impl;

import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import com.seata.demo.mapper.StorageTblMapper;
import com.seata.demo.service.StorageService;
import com.seata.demo.common.dto.CommodityDTO;
import com.seata.demo.common.res.Resp;

import io.seata.core.context.RootContext;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.slf4j.Slf4j;

/**
* @comments
* @author  zg
* @date 2021年2月9日
*/
@AllArgsConstructor
@Slf4j
@Service
public class StorageServiceImpl implements StorageService {

    private StorageTblMapper storageTblMapper;
    
    @Override
    public Resp<CommodityDTO> deduct(String commodityCode, int deductCount) {
        /*String xid = RootContext.getXID();
        String xid1 = GlobalTransactionContext.getCurrentOrCreate().getXid();
        log.info("xid={}, xid1={}", xid, xid1);*/
        CommodityDTO commodity = storageTblMapper.selectCommodity(commodityCode);
        if(commodity == null) {
            log.warn("商品不存在！commodityCode={}, deductCount={}", commodityCode, deductCount);
            return Resp.error("商品不存在");
        }
        
        int count = storageTblMapper.deduct(commodityCode, deductCount);
        if(count > 0) {
            log.info("扣减库存成功。commodityCode={}，deductCount={}", commodityCode, deductCount);
            return Resp.success(commodity);
        }
        log.warn("扣减库存失败！commodityCode={}，deductCount={}", commodityCode, deductCount);
        return Resp.failure();
    }

    /*@Override
    public Resp<CommodityDTO> selectCommodity(String commodityCode) {
        CommodityDTO commodity = storageTblMapper.selectCommodity(commodityCode);
        return Resp.success(commodity);
    }*/
    
}
